package com.an.cloud.mygateway;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 我全局过滤器
 *
 * @author: ANHE
 * @createDate: 2024/03/20
 * @version: 1.0.0
 */
@Component
@Slf4j
public class MyGlobalFilter implements GlobalFilter, Ordered {
    /**
     * 过滤器
     *
     * @param exchange 交换
     * @param chain    链
     * @return {@link Mono }<{@link Void }>
     * @author: ANHE
     * @createDate: 2024/03/20
     * @version: 1.0.0
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //记录开始时间
        exchange.getAttributes().put("begin_visit_time", System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Long beginVisitTime = exchange.getAttribute("begin_visit_time");
            if (beginVisitTime != null) {
                log.info("访问接口主机：" + exchange.getRequest().getURI().getHost());
                log.info("访问接口端口：" + exchange.getRequest().getURI().getPort());
                log.info("访问接口URL：" + exchange.getRequest().getURI().getPath());
                log.info("访问接口URL后面参数：" + exchange.getRequest().getURI().getRawQuery());
                long endVisitTime = System.currentTimeMillis();
                log.info("访问接口时长：" + (endVisitTime - beginVisitTime) + "毫秒\n");
            }
        }));
    }

    /**
     * 执行顺序
     *
     * @return int
     * @author: ANHE
     * @createDate: 2024/03/20
     * @version: 1.0.0
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
